
from pykd import *
import sys
#
#
#

def loadSymbols():

   global nt
   nt = loadModule( "nt" )

def getObjectName(objHeader):

    if (ptrWord(getOffset("nt", "NtBuildNumber")) >= 7600):
        offsetIndex = objHeader.InfoMask & 0x2
        offset = ptrByte( nt.ObpInfoMaskToOffset + offsetIndex) 
        return typedVar( "nt", "_OBJECT_HEADER_NAME_INFO",  objHeader.getAddress() - offset )
    else:
        return typedVar( "nt", "_OBJECT_HEADER_NAME_INFO",  objHeader.getAddress() - objHeader.NameInfoOffset )    

def getObjectType(objHeader):
   
    if (ptrWord(getOffset("nt", "NtBuildNumber")) >= 7600):
        return ptrPtr(nt.ObTypeIndexTable + (ptrSize() * objHeader.TypeIndex))
    else:
        return objHeader.Type            


def getObjectInDir( dirObj, objName ):

    if objName.find( "\\" ) != -1:
        ( dirSubName, objSubName ) =  objName.split("\\", 1)
    else:
        dirSubName = objName
 
    for i in range( 0, 37 ):

       if dirObj.HashBuckets[i] != 0:
          dirEntry = typedVar( "nt", "_OBJECT_DIRECTORY_ENTRY", dirObj.HashBuckets[i] )

          while dirEntry != 0:
              
              objHeader = containingRecord( dirEntry.Object, "nt", "_OBJECT_HEADER", "Body" )
              objName = getObjectName( objHeader )
              name = loadUnicodeString( objName.Name.getAddress() )

              if name.lower() == dirSubName.lower():
                  if getObjectType( objHeader ) == ptrPtr( nt.ObpDirectoryObjectType ):
                      return getObjectInDir( typedVar( "nt", "_OBJECT_DIRECTORY", dirEntry.Object), objSubName )             
                  else:
                      return  dirEntry.Object

              if dirEntry.ChainLink != 0:
                  dirEntry = typedVar( "nt", "_OBJECT_DIRECTORY_ENTRY", dirEntry.ChainLink )
              else:
                  dirEntry = 0    
                                                                          
def getObjectByName( objName ):
    
    if len(objName)==0: 
        return None

    if objName[0] != '\\':
        return None
    
    loadSymbols()

    rootDir = typedVar( "nt", "_OBJECT_DIRECTORY", ptrPtr( nt.ObpRootDirectoryObject ) )
   
    return getObjectInDir( rootDir, objName[1:] )
